package main

import (
	"crypto/tls"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"time"

	"gopkg.in/gomail.v2"
)

var (
	ip    string
	count int
)

//DSMWPTZPORWXKDTY
func main() {
	log.SetFlags(log.Llongfile | log.LstdFlags)

	// 邮件接收方
	mailTo := []string{
		"srandroid@163.com",
	}

	c := time.NewTicker(1 * time.Hour)
	for range c.C {
		go func() {
			resp, err := http.Get("http://ipinfo.io")
			if err != nil {
				log.Printf("请求http地址：%v\n", err)
				return
			}
			defer resp.Body.Close()
			bs, err := io.ReadAll(resp.Body)
			if err != nil {
				log.Printf("读取http响应：%v\n", err)
				return
			}

			result := make(map[string]string, 0)
			err = json.Unmarshal(bs, &result)
			if err != nil || result["ip"] == "" {
				log.Printf("解释响应json数据：%v\n", err)
				return
			}

			if ip == result["ip"] {
				return
			}

			ip = result["ip"]
			err = SendMail(mailTo, ip)
			if err != nil {
				log.Printf("发送邮件：%v\n", err)
				return
			}
			log.Println("发送邮件成功")
		}()
	}
}

func SendMail(mailTo []string, body string) error {
	// 设置邮箱主体
	mailConn := map[string]string{
		"user": "srandroid@163.com", //发送人邮箱（邮箱以自己的为准）
		"pass": "DSMWPTZPORWXKDTY",  //发送人邮箱的密码，现在可能会需要邮箱 开启授权密码后在pass填写授权码
		"host": "smtp.163.com",      //邮箱服务器（此时用的是qq邮箱）
	}

	m := gomail.NewMessage(
		gomail.SetEncoding(gomail.Base64),
	)
	m.SetHeader("From", m.FormatAddress(mailConn["user"], "公网IP")) // 添加别名
	m.SetHeader("To", mailTo...)                                   // 发送给用户(可以多个)
	m.SetHeader("Subject", time.Now().Format("2006/01/02 15:04"))  // 设置邮件主题
	m.SetBody("text/html", body)                                   // 设置邮件正文

	d := gomail.NewDialer(mailConn["host"], 465, mailConn["user"], mailConn["pass"]) // 设置邮件正文
	d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	err := d.DialAndSend(m)
	return err
}
